package com.toy.service.impl;


import com.toy.service.FileService;
import com.toy.vo.ImageVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author tystart
 * @create 2022-08-25-16:38
 */
@Service
@PropertySource("classpath:/image.properties")
public class FileServiceImpl implements FileService {

    @Value("${image.localPathDir}")
    private String localPathDir;
    @Value("${image.localUrlPath}")
    private String localUrlPath;

    @Override
    public ImageVO upload(MultipartFile file) throws IOException {
        //获取文件名称
        String filename = file.getOriginalFilename();
        //名字转换小写
        filename = filename.toLowerCase();
        //1、后缀名检查jpg png jpeg gif
        if(!filename.matches("^.+\\.(jpg|png|jpeg|gif)$")){
            return null;
        }

        //2、图片内容的检查（判断不是图片以外的文件，病毒、木马)
        BufferedImage img = ImageIO.read(file.getInputStream());
        if (img.getWidth()==0 || img.getHeight() == 0){
            return null;
        }

        //3、按照日期分目录存储，便于从时间维度管理
//        String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
//
//        String localDir = localPathDir + datePath;

//        System.out.println(localDir+"========================================");
        File dirFile = new File(localPathDir);
        if (!dirFile.exists()){//如果文件不存在
            dirFile.mkdirs();//创建
        }

        //4、解决重名
        String fileType = filename.substring(filename.lastIndexOf("."));
        String uuidStr = UUID.randomUUID().toString().replace("-", "");
        String realFileName = uuidStr + fileType;
//        System.out.println(realFileName+"========================================");
        //构建file对象，表示硬盘中某个文件
        String realFileFullPath = localPathDir + realFileName;
        File realFile = new File(realFileFullPath);
        file.transferTo(realFile);

        String virtualPath = localPathDir + realFileName;
        String urlPath = localUrlPath + virtualPath;
        return new ImageVO(virtualPath,urlPath,realFileName);
    }

    @Override
    public void removeFile(String virtualPath) {
        String filePath = localPathDir + virtualPath;
//        System.out.println(filePath+"===========================================");
        File file = new File(filePath);
        file.delete();
    }
    @Override
    @Transactional
    public void removeFiles(List<String> virtualPaths){
        for (String virtualPath: virtualPaths){
            removeFile(virtualPath);
        }
    }
}
